package com.magnificent.atlantis.server.ui.panels.user.dialog;

import com.magnificent.atlantis.common.entity.ServerUser;
import com.magnificent.atlantis.server.AtlantisServerConstants;
import com.magnificent.atlantis.server.resources.AtlantisServerResources;
import com.magnificent.commons.ui.dialogs.DialogConnector;
import com.magnificent.commons.ui.dialogs.DialogFactory;
import com.magnificent.commons.utils.crypt.MD5;
import com.magnificent.helpers.CommonUIHelper;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * ServerUser: Babanin
 * Date: 04.04.2009
 * Time: 12:25:29
 */
public class UserDialog extends JDialog {
    private static final String DEFAULT_PASSWORD = "default";

    private JTextField nameField;
    private JTextField surnameField;
    private JTextField loginField;

    private JPasswordField newPassword;
    private JPasswordField newPasswordRetype;

    private ServerUser serverUser;
    private boolean edit;
    private DialogConnector<ServerUser> connector;

    private boolean clicked;

    public UserDialog(DialogConnector<ServerUser> connector) {
        this(null, connector);
    }

    public UserDialog(ServerUser ServerUser, DialogConnector<ServerUser> connector) {
        edit = ServerUser != null;
        this.connector = connector;
        this.serverUser = ServerUser == null ? new ServerUser() : ServerUser;

        initialize();
        initializeControls();
        initializeView();
    }

    private void initialize() {
        clicked = false;
        setIconImage(AtlantisServerResources.ICON.getImage());
    }

    private void initializeControls() {
        nameField = new JTextField(AtlantisServerConstants.DEFAULT_FIELD_LENGTH);
        surnameField = new JTextField(AtlantisServerConstants.DEFAULT_FIELD_LENGTH);
        loginField = new JTextField(AtlantisServerConstants.DEFAULT_FIELD_LENGTH);

        newPassword = new JPasswordField(AtlantisServerConstants.DEFAULT_FIELD_LENGTH);
        newPasswordRetype = new JPasswordField(AtlantisServerConstants.DEFAULT_FIELD_LENGTH);

        if (edit) {
            nameField.setText(serverUser.getName());
            surnameField.setText(serverUser.getSurname());
            loginField.setText(serverUser.getLogin());

            newPassword.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (!clicked) {
                        clicked = true;
                        newPassword.setText("");
                        newPasswordRetype.setText("");
                    }
                }
            });
            newPassword.setText(DEFAULT_PASSWORD);
            newPasswordRetype.setText(DEFAULT_PASSWORD);

            newPassword.setToolTipText("Don't edit if password not changed");
            newPasswordRetype.setToolTipText("Don't edit if password not changed");
        }
    }

    private void initializeView() {
        setModal(true);
        setTitle((edit ? "Edit" : "Create new") + " user");

        add(CommonUIHelper.createGridPanel(5, 5, 5, 5, 5, 2,
                "Login: ", edit ?
                        new JLabel("<html><b>" + serverUser.getLogin() + "</b></html>") :
                        loginField,
                "Surname: ", surnameField,
                "Name: ", nameField,
                "New password*: ", newPassword,
                "Repeat password*: ", newPasswordRetype
        ), BorderLayout.CENTER);

        add(
                CommonUIHelper.packInPanel(CommonUIHelper.createHorizontalBox(
                        new JButton(new AbstractAction(edit ? "Save" : "Create") {
                            public void actionPerformed(ActionEvent e) {
                                if (checkFields()) {
                                    connector.objectSelected(serverUser);
                                    UserDialog.this.dispose();
                                }
                            }
                        }), new JButton(new AbstractAction("Cancel") {
                            public void actionPerformed(ActionEvent e) {
                                UserDialog.this.dispose();
                            }
                        })
                ), BorderLayout.LINE_END
                ), BorderLayout.SOUTH
        );

        getRootPane().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        pack();
        setLocationRelativeTo(null);
    }

    private boolean checkFields() {
        String name = nameField.getText();
        String surname = surnameField.getText();

        String password = new String(newPassword.getPassword());
        String passwordRetype = new String(newPasswordRetype.getPassword());

        if (name.equals("")) {
            DialogFactory.error("Name can't be empty string", UserDialog.this);
            return false;
        }

        if (surname.equals("")) {
            DialogFactory.error("Surname can't be empty string", UserDialog.this);
            return false;
        }

        if (edit) {
            if (password.length() != 0) {
                if (!password.equals(passwordRetype)) {
                    DialogFactory.error("Passwords can't be different", UserDialog.this);
                    return false;
                }
            }

            serverUser.setName(name);
            serverUser.setSurname(surname);

            if (clicked) {
                if (password.length() != 0) {
                    serverUser.setPassword(MD5.crypt(password));
                }

                if (password.equals("")) {
                    DialogFactory.error("Password can't be empty string", UserDialog.this);
                    return false;
                }

                if (!password.equals(passwordRetype)) {
                    DialogFactory.error("Passwords can't be different", UserDialog.this);
                    return false;
                }

                serverUser.setPassword(MD5.crypt(password));
            }
        } else {
            String login = loginField.getText();

            if (login.equals("")) {
                DialogFactory.error("Login can't be empty string", UserDialog.this);
                return false;
            }

            if (password.equals("")) {
                DialogFactory.error("Password can't be empty string", UserDialog.this);
                return false;
            }

            if (!password.equals(passwordRetype)) {
                DialogFactory.error("Passwords can't be different", UserDialog.this);
                return false;
            }

            serverUser.setName(name);
            serverUser.setSurname(surname);
            serverUser.setLogin(login);
            serverUser.setPassword(MD5.crypt(password));
            serverUser.setClearPassword(password);
        }

        return true;
    }

    public static void createUser(DialogConnector<ServerUser> connector) {
        UserDialog userDialog = new UserDialog(connector);
        userDialog.setVisible(true);
    }

    public static void editUser(ServerUser u, DialogConnector<ServerUser> connector) {
        UserDialog userDialog = new UserDialog(u, connector);
        userDialog.setVisible(true);
    }
}
